import styled from 'styled-components'
import {useEffect, useLayoutEffect, useRef, useState} from 'react'
import {
  $_all_look,
  $_banner,
  $_cultural_newsstand,
  $_featured_column_list,
  $_hot_activity,
  $_hot_culture_card, $_recommend_article_list, $_recommend_audio_list,
  $_recommend_cultural_list,
  $_recommend_database_list, $_recommend_influential_person_list,
  $_recommend_ip_list,
  $_recommend_journal_list
} from '@/api/index.js'
import {
  MSwiper,
  EverybodyIsWatching,
  MLabel,
  ActiveItem,
  CulturalCardsItem,
  FeaturedColumns,
  CulturalItem,
  JournalistStyle,
  NewspaperSubscriptionsItem,
  CulturalAndCreativeItem,
  IpDatabaseItem,
  EditorInChiefRoundtable, BigCoffeeItem, TiaoItem
} from '@/views/home/components/index.jsx'
import {getImageUrl, hexToRgb} from '@/utils/utils.js'
import React from 'react'
import {$_showcaseList} from '@/api/common.js'
import Masonry from 'react-masonry-css'
const Container = styled.div`
    height: 100%;
    background: #F4F4F4;

    .box-1 {
        background: #F4F4F4;
        padding-bottom: 40px;

        .recommendation-box {
            width: 1200px;
            margin: 0 auto;
            display: flex;
        }

        .hot-box {
            width: 1200px;
            margin: 0 auto;
            display: flex;
            margin-top: 20px;;

            .hot-active {
                width: 800px;

                .active-list {
                    width: 800px;
                    height: 816px;
                    background: #FFF;
                    box-sizing: border-box;
                    padding: 26px;
                    display: grid;
                    grid-template-columns: repeat(3, 231px);
                    gap: 24px 28px;
                    margin-top: 20px;
                }
            }

            .hot-card {
                width: 380px;
                margin-left: 20px;

                .hot-card-box {
                    width: 380px;
                    height: 816px;
                    background: #FFF;
                    box-sizing: border-box;
                    margin-top: 20px;
                    padding: 26px 10px;

                    .item {
                        margin-bottom: 26px;

                        &:last-child {
                            margin-bottom: 0;
                        }
                    }
                }

                .checkMore {
                    display: flex;
                    align-items: center;
                    width: fit-content;
                    margin: 0 auto;
                    cursor: pointer;

                    .icon {
                        width: 14px;
                        height: 14px;
                        margin-left: 4px;
                    }

                    .text {
                        color: #006647;
                        font-size: 16px;
                        font-weight: 500;
                        letter-spacing: 0.48px;
                    }
                }
            }
        }

        .featured-columns {
            width: 1200px;
            margin: 0 auto;
            margin-top: 40px;

            .featured-columns-list {
                margin-top: 20px;
                display: grid;
                gap: 0 27px;
                grid-template-columns: repeat(4, 280px);
            }
        }


    }

    .box-2 {
        background: #E1E1E1;
        padding: 30px 0;

        .bk-box {
            width: 1200px;
            margin: 0 auto;

            .tab-list-box {
                display: flex;
                box-sizing: border-box;
                padding: 0 5px;
                margin-top: 20px;

                .tab-list {
                    flex: 1;
                    display: flex;
                    //gap: 0 61px;
                    overflow-x: auto;
                    white-space: nowrap;

                    &::-webkit-scrollbar {
                        display: none;
                    }

                    -ms-overflow-style: none; /* IE 和 Edge */
                    scrollbar-width: none; /* Firefox */

                    .tab-item {
                        color: #1c1c1c;
                        font-size: 16px;
                        font-weight: 700;
                        line-height: 16px;
                        cursor: pointer;
                        margin-right: 61px;

                        &:last-child {
                            margin-right: 0;
                        }
                    }

                    .active-item {
                        border-bottom: 2px solid #006647;
                        color: #237A5F;
                        font-size: 18px;
                        line-height: 18px;
                    }
                }

                .leftIcon {
                    width: 25px;
                    height: 25px;
                    cursor: pointer;
                }

                .rightIcon {
                    width: 25px;
                    height: 25px;
                    cursor: pointer;
                }
            }

            .line {
                margin: 0 auto;
                margin-top: 19px;
                padding: 0 25px;
                box-sizing: border-box;

                .center {
                    height: 1px;
                    background: #66666666;
                    flex: 1;
                }
            }
        }
    }

    .box-3 {
        background: #F4F4F4;
        padding: 40px 0;

        .journalist-style {
            width: 1200px;
            margin: 0 auto;
        }

        .cultural-bazaar {
            width: 1200px;
            margin: 0 auto;
            margin-top: 40px;

            .newspaper-subscriptions {
                margin-top: 20px;

                .newspaper-subscriptions-list {
                    display: grid;
                    grid-template-columns: repeat(2, 578px);
                    gap: 20px 42px;
                    margin-top: 20px;
                }
            }

            .cultural-creativity {
                margin-top: 20px;

                .cultural-creativity-list {
                    display: grid;
                    grid-template-columns: repeat(2, 580px);
                    gap: 20px 29px;
                    margin-top: 20px;
                }
            }
            .original-ip-database{
                margin-top: 20px;
                .original-ip-database-list {
                    display: grid;
                    grid-template-columns: repeat(4, 280px);
                    gap: 0px 26px;
                    margin-top: 20px;
                }
            }
        }
    }
    .box-4{
        background: #E8E8E8;
        padding: 30px 0;
        .editor-roundtable{
            width: 1200px;
            margin: 0 auto;
        }
    }
    .box-5{
        padding: 40px 0 90px 0;
        background: #F4F4F4;
        .big-coffee-forum{
            margin:  0 auto;
            width: 1200px;
            .big-coffee-forum-list{
                display: grid;
                grid-template-columns: repeat(2,579px);
                gap: 20px 30px;
                margin-top: 20px;
            }
        }
        .tiao{
            margin:  0 auto;
            width: 1200px;
            margin-top: 40px;
            .my-masonry-grid {
                display: grid;
                grid-template-columns: repeat(4,280px);
                gap: 0 27px;
                margin-top: 20px;
            }
            .my-masonry-grid_column{
                width: 280px !important;
            }
            .my-masonry-grid_column > div {
                margin-bottom: 20px;
                &:last-child{
                    margin-bottom: 0;
                }
            }
        }
    }

`


export default function HomePage() {
  const [bannerList, setBannerList] = useState([])
  const [allLookList, setAllLookList] = useState([])
  const [hotActivityList, setHotActivityList] = useState([])
  const [hotCultureList, setHotCultureList] = useState([])
  const [featuredColumnList, setFeaturedColumnList] = useState([])
  const [culturalNewsstandList, setCulturalNewsstandList] = useState([])
  const [recommendCultureList, setRecommendCultureList] = useState([])
  const [activeId, setActiveId] = useState('')
  const [showcaseList, setShowcaseList] = useState([])
  const [journalList, setJournalList] = useState([])
  const [recommendIpList, setRecommendIpList] = useState([])
  const [recommendDatabaseList, setRecommendDatabaseList] = useState([])
  const [recommendAudioList, setRecommendAudioList] = useState([])
  const [recommendPersonList, setRecommendPersonList] = useState([])
  const [recommendArticleList,setRecommendArticleList] = useState([])
  const [activeIndex, setActiveIndex] = useState(0)

  useEffect(() => {
    // Promise.all([
    //   getBannerList(),
    //   getAllLooK(),
    //   getHotActivity(),
    //   getHotCultureCard()
    // ]).then(() => {
    //   console.log(111)
    // }).finally(()=>{
    //   console.log(222)
    // })
    getBannerList()
    getAllLooK()
    getHotActivity()
    getHotCultureCard()
    getFeaturedColumnList()
    getCulturalNewsstand()
    getShowcaseList()
    getRecommendJournalList()
    getRecommendCulturalList()
    getRecommendIPList()
    getRecommendDatabaseList()
    getRecommendAudioList()
    getRecommendInfluentialPersonList()
    getRecommendArticleList()
  }, [])

  //轮播图
  async function getBannerList() {
    const res = await $_banner({
      module_type: 1
    })
    if (res.result.status_info.status_code !== 100) {
      setBannerList([])
      return
    }
    setBannerList(res.result.banner_list)
  }

  //大家都在看
  async function getAllLooK() {
    const params = {
      module_type: 1
    }
    const res = await $_all_look(params)
    if (res.result.status_info.status_code !== 100) {
      setAllLookList([])
      return
    }
    setAllLookList(res.result.trending_resource_list)
  }

  // 热门活动
  async function getHotActivity() {
    const params = {
      cover_format: "s"
    }
    const res = await $_hot_activity(params)
    if (res.result.status_info.status_code !== 100) {
      setHotActivityList([])
      return
    }
    setHotActivityList(res.result.hot_activity_list)
  }

   // 热门文化名片
  async function getHotCultureCard() {
    const params = {
      cover_format: "s"
    }
    const res = await $_hot_culture_card(params)
    if (res.result.status_info.status_code !== 100) {
      setHotCultureList([])
      return
    }
    setHotCultureList(res.result.hot_presses_list.map(item => ({
      ...item,
      theme_color_rgb: hexToRgb(item.theme_color)
    })))
  }
 // 精选专栏
  async function getFeaturedColumnList() {
    const params = {
      cover_format: "m"
    }
    const res = await $_featured_column_list(params)

    if (res.result.status_info.status_code !== 100) {
      setFeaturedColumnList([])
      return
    }
    setFeaturedColumnList(res.result.featured_column_list)
  }
 //文化报刊亭
  async function getCulturalNewsstand() {
    const params = {
      cover_format: "h"
    }
    const res = await $_cultural_newsstand(params)
    if (res.result.status_info.status_code !== 100) {
      setCulturalNewsstandList([])

      return
    }
    const list = res.result.cultural_newsstand_resource_list
    setCulturalNewsstandList(list)
    setActiveId(list[0]?.magazine_id)
  }

  const tabList = useRef()
  const activeItem = culturalNewsstandList.find(item => item.magazine_id === activeId)
  const [showScrollButtons, setShowScrollButtons] = useState(false)

  function handleScroll(type) {
    if (type === 1) {
      tabList.current.scrollBy({
        left: -100,
        behavior: 'smooth'
      })
    } else {
      tabList.current.scrollBy({
        left: 100,
        behavior: 'smooth'
      })
    }
  }

  function handleItem(id) {
    setActiveId(id)
  }

  useLayoutEffect(() => {
    if (activeId === '') return
    const activeItem = document.querySelector('.active-item');
    const tabList = document.querySelector('.tab-list');
    const tabRect = tabList.getBoundingClientRect();
    const activeRect = activeItem.getBoundingClientRect();
    if (tabList.scrollWidth > tabList.clientWidth) {
      setShowScrollButtons(true)
    } else {
      setShowScrollButtons(false)
    }
    if (activeRect.left < tabRect.left) {
      tabList.scrollBy({
        left: activeRect.left - tabRect.left,
        behavior: 'smooth'
      });
    }
    if (activeRect.right > tabRect.right) {
      tabList.scrollBy({
        left: activeRect.right - tabRect.right,
        behavior: 'smooth'
      });
    }
  }, [activeId]); // 依赖 activeId，状态更新时执行

   //刊社风采
  async function getShowcaseList() {
    const params = {
      module_type: 1
    }
    const res = await $_showcaseList(params)
    if (res.result.status_info.status_code !== 100) {
      setShowcaseList([])
      return
    }
    setShowcaseList(res.result.banner_list)
  }
  //报刊订阅
  async function getRecommendJournalList() {
    const params = {
      cover_format: "l"
    }
    const res = await $_recommend_journal_list(params)
    if (res.result.status_info.status_code !== 100) {
      setJournalList([])
      return
    }
    setJournalList(res.result.recommend_journal_list)
  }
 // 文创周边
  async function getRecommendCulturalList() {
    const params = {
      cover_format: "m"
    }
    const res = await $_recommend_cultural_list(params)
    if (res.result.status_info.status_code !== 100) {
      setRecommendCultureList([])
      return
    }
    setRecommendCultureList(res.result.recommend_cultural_list)
  }
  //原创IP
  async function getRecommendIPList() {
    const params = {
      cover_format: "m"
    }
    const res = await $_recommend_ip_list(params)
    if (res.result.status_info.status_code !== 100) {
      setRecommendIpList([])
      return
    }
    setRecommendIpList(res.result.recommend_ip_list)
  }
  //行业智库
  async function getRecommendDatabaseList() {
    const params = {
      cover_format: "m"
    }
    const res = await $_recommend_database_list(params)
    if (res.result.status_info.status_code !== 100) {
      setRecommendDatabaseList([])
      return
    }
    setRecommendDatabaseList(res.result.recommend_database_list)
  }
  // 主编圆桌
  async function getRecommendAudioList() {
    const params = {
      cover_format: "l"
    }
    const res = await $_recommend_audio_list(params)
    if (res.result.status_info.status_code !== 100) {
      setRecommendAudioList([])
      return
    }
    setRecommendAudioList(res.result.recommend_audio_list)
    let index =activeIndex
    setInterval(()=>{
      index = (index + 1)%res.result.recommend_audio_list.length
      setActiveIndex(index)
    },5000)
  }
  //大咖讲坛
  async function getRecommendInfluentialPersonList() {
    const params = {
      cover_format: "m"
    }
    const res = await $_recommend_influential_person_list(params)
    if (res.result.status_info.status_code !== 100) {
      setRecommendPersonList([])
      return
    }
    setRecommendPersonList(res.result.recommend_influential_person_list.map(item=>{
      return {
        ...item,
        tag: item.tag_name.length ? item.tag_name.split(",") : []
      }
    }))
  }
  //头条
  async function getRecommendArticleList() {
    const params = {
      cover_format: "m"
    }
    const res = await $_recommend_article_list(params)
    if (res.result.status_info.status_code !== 100) {
      setRecommendArticleList([])
      return
    }
    setRecommendArticleList(res.result.article_list)
  }

  return (
      <>
        <Container>
          <div className="box-1">
            <div className={'recommendation-box'}>
              <MSwiper list={bannerList}/>
              <EverybodyIsWatching list={allLookList}/>
            </div>
            <div className={'hot-box'}>
              <div className={'hot-active'}>
                <MLabel leftText={'热门活动'} rightText={'查看更多'}></MLabel>
                <div className={'active-list'}>
                  {hotActivityList.map((item, index) => <ActiveItem key={index} detail={item}/>)
                  }
                </div>
              </div>
              <div className={'hot-card'}>
                <MLabel leftText={'热门文化名片'}></MLabel>
                <div className={'hot-card-box'}>
                  {
                    hotCultureList.map((item, index) => <CulturalCardsItem key={index} detail={item}/>)
                  }
                  <div className={'checkMore'}>
                    <div className="text">查看更多</div>
                    <img src={getImageUrl('specialColumn/right.png')} alt="" className="icon"/>
                  </div>
                </div>

              </div>
            </div>
            <div className={'featured-columns'}>
              <MLabel leftText={'精选专栏'}></MLabel>
              <div className={'featured-columns-list'}>
                {featuredColumnList.map((item, index) => <FeaturedColumns key={index} detail={item}/>)}
              </div>
            </div>
          </div>
          <div className={'box-2'}>
            <div className={'bk-box'}>
              <MLabel leftText={'文化报刊亭'}></MLabel>
              <div className={'tab-list-box'} style={{padding: showScrollButtons ? '0' : '0 25px'}}>
                {showScrollButtons &&
                    <img src={getImageUrl('scroll_left.png')} alt="" className={'leftIcon'} onClick={() => {
                      handleScroll(1)
                    }}/>}

                <div className={'tab-list'} ref={tabList}>
                  {culturalNewsstandList.map((item, index) => <div
                      className={`tab-item ${item.magazine_id === activeId ? 'active-item' : ''}`} key={index}
                      onClick={() => {
                        handleItem(item.magazine_id)
                      }}>
                    {item.magazine_name}
                  </div>)}
                </div>
                {showScrollButtons &&
                    <img src={getImageUrl('scroll_right.png')} alt="" className={'rightIcon'} onClick={() => {
                      handleScroll(2)
                    }}/>}

              </div>
              <div className={'line'}>
                <div className={'center'}></div>
              </div>
              <CulturalItem activeItem={activeItem}/>
            </div>
          </div>
          <div className={'box-3'}>
            <div className={'journalist-style'}>
              <MLabel leftText={'刊社风采'}></MLabel>
              <JournalistStyle list={showcaseList}></JournalistStyle>
            </div>
            <div className={'cultural-bazaar'}>
              <MLabel leftText={'文化市集'}></MLabel>
              <div className={'newspaper-subscriptions'}>
                <MLabel leftText={'报刊订阅'} type={2}></MLabel>
                <div className={'newspaper-subscriptions-list'}>
                  {journalList.map((item, index) => <NewspaperSubscriptionsItem key={index}
                                                                                detail={item}></NewspaperSubscriptionsItem>)}
                </div>
              </div>
              <div className={'cultural-creativity'}>
                <MLabel leftText={'文创周边'} type={2}></MLabel>
                <div className={'cultural-creativity-list'}>
                  {recommendCultureList.map((item, index) => {
                    return (<CulturalAndCreativeItem key={index} detail={item}></CulturalAndCreativeItem>)
                  })}
                </div>
              </div>
              {/*<div className={'original-ip-database'}>*/}
              {/*  <MLabel leftText={'原创Ip'} type={2}></MLabel>*/}
              {/*  <div className={'original-ip-database-list'}>*/}
              {/*    {recommendIpList.map((item, index) => {*/}
              {/*      return (<IpDatabaseItem key={index} detail={item}></IpDatabaseItem>)*/}
              {/*    })}*/}
              {/*  </div>*/}
              {/*</div>*/}
              <div className={'original-ip-database'}>
                <MLabel leftText={'行业智库'} type={2}></MLabel>
                <div className={'original-ip-database-list'}>
                  {recommendDatabaseList.map((item, index) => {
                    return (<IpDatabaseItem key={index} detail={item}></IpDatabaseItem>)
                  })}
                </div>
              </div>

            </div>
          </div>
          <div className={'box-4'}>
            <div className={'editor-roundtable'}>
              <MLabel leftText={'主编圆桌'} rightText={'查看更多'}></MLabel>
              <EditorInChiefRoundtable list={recommendAudioList} activeIndex={activeIndex}></EditorInChiefRoundtable>
            </div>
          </div>
          <div className={'box-5'}>
            <div className={'big-coffee-forum'}>
              <MLabel leftText={'大咖讲坛'} rightText={'查看更多'}></MLabel>
              <div className={'big-coffee-forum-list'}>
                {recommendPersonList.map((item, index) => {
                  return (<BigCoffeeItem key={index} detail={item}></BigCoffeeItem>)
                })}
              </div>
            </div>
            <div className={'tiao'}>
              <MLabel leftText={'头条'} rightText={'查看更多'}></MLabel>
              <Masonry   breakpointCols={4}
                         className="my-masonry-grid"  columnClassName="my-masonry-grid_column">
                {recommendArticleList.map((item, index) =>
                   <TiaoItem key={index} detail={item}></TiaoItem>)
                }
              </Masonry>
            </div>
          </div>
        </Container>
      </>

  );
}